package uid

import (
	"fmt"
	"github.com/sony/sonyflake"
	"sync"
	"time"
)

var sf *SonyFlake
var lock = sync.Mutex{}

// SonyFlake 雪花算法产生的UID的处理,生成的ID大概在14位的
type SonyFlake struct {
	sonyFlake     *sonyflake.Sonyflake
	sonyMachineID uint16
}

func (s *SonyFlake) GetMachineID() uint16 {
	return s.sonyMachineID
}

func new(machineId uint16) *SonyFlake {
	var st time.Time
	st, _ = time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
	settings := sonyflake.Settings{
		StartTime: st,
		MachineID: func() (uint16, error) {
			return machineId, nil
		},
	}
	sf = &SonyFlake{
		sonyFlake:     sonyflake.NewSonyflake(settings),
		sonyMachineID: machineId,
	}
	return sf
}

func (s *SonyFlake) GenID() (id uint64, err error) {
	if s == nil || s.sonyFlake == nil {
		err = fmt.Errorf("uid create error")
		return
	}
	id, err = s.sonyFlake.NextID()
	return
}

// GenID 获取ID
func GenID() (id uint64, err error) {
	instance := SingleInstance()
	id, err = instance.GenID()
	return
}

func (s *SonyFlake) GenString() (string, error) {
	if s == nil || s.sonyFlake == nil {
		return "", fmt.Errorf("uid create error")
	}
	id, err := s.sonyFlake.NextID()
	if err != nil {
		return "", fmt.Errorf("uid create error")
	}
	return fmt.Sprintf("%v", id), nil
}

// SingleInstance 单机版，默认的处理
func SingleInstance() *SonyFlake {
	if sf == nil {
		lock.Lock()
		defer lock.Unlock()
		if sf != nil {
			return sf
		}
		sf = new(1)
		return sf
	}
	return sf
}

// NewSonyFlake 自定义创建初始化一个的处理
// 如果重新换ID，则不会生效处理
func NewSonyFlake(machineID uint16) *SonyFlake {
	if sf == nil {
		lock.Lock()
		defer lock.Unlock()
		if sf != nil {
			return sf
		}
		sf = new(machineID)
		return sf
	}
	return sf
}
